package com.jumi.microservice.service.jd.timingtask;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.kplunion.OrderService.request.query.OrderRowReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.OrderRowResp;
import com.jd.open.api.sdk.request.kplunion.UnionOpenOrderRowQueryRequest;
import com.jd.open.api.sdk.response.kplunion.UnionOpenOrderRowQueryResponse;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.entity.CouponOrder;
import com.jumi.microservice.enumerate.SourceEnum;
import com.jumi.microservice.mapper.CouponOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class TiMingTaskServiceImpl {


    @Resource
    CouponOrderMapper couponOrderMapper;

    private static final Logger logger = LoggerFactory.getLogger(JdOrderTiMingTask.class);


    private static JdClient client = new DefaultJdClient("https://api.jd.com/routerjson", "", "c02c79ce1d4aee0500f6c4c7766700fc", "7d361f4207934d438fe775a854c30e3a");

    /**
     * 更新
     *
     * @throws Exception
     */
    public void orderTiMingTask() throws Exception {
        logger.info("定时修改京东订单");
        boolean data = true;
        int pageIndex = 1;
        List<OrderRowResp> orderRowResps = new ArrayList<>();
//        JdClient client = new DefaultJdClient("https://api.jd.com/routerjson", "", "c02c79ce1d4aee0500f6c4c7766700fc", "7d361f4207934d438fe775a854c30e3a");
        while (data) {
            UnionOpenOrderRowQueryRequest request = new UnionOpenOrderRowQueryRequest();
            OrderRowReq orderReq = new OrderRowReq();
            orderReq.setFields("goodsInfo");
            orderReq.setPageIndex(pageIndex);
            orderReq.setPageSize(500);
            orderReq.setType(3);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.MINUTE, -59);
//            orderReq.setStartTime(DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss"));
//            orderReq.setEndTime(DateUtil.getTime());
            orderReq.setStartTime("2021-01-18 10:22:08");
            orderReq.setEndTime("2021-01-18 10:24:08");
            request.setOrderReq(orderReq);
            UnionOpenOrderRowQueryResponse response = client.execute(request);
            logger.info("开始更新订单时间[{}]", DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss"));
            logger.info("结束更新订单时间[{}]", DateUtil.getTime());
            logger.info("拉取订单的信息为[{}]", JSON.toJSONString(response));
            if (response.getQueryResult().getHasMore() != null) {
                if (response.getQueryResult().getHasMore()) {
                    logger.info("拉取 继续循环");
                    List<OrderRowResp> orderRowRespList = Arrays.asList(response.getQueryResult().getData());
                    orderRowResps.addAll(orderRowRespList);
                } else {
                    logger.info("拉取 结束循环");
                    data = false;
                    List<OrderRowResp> orderRowRespList = Arrays.asList(response.getQueryResult().getData());
                    orderRowResps.addAll(orderRowRespList);
                }
            } else {
                return;
            }
            pageIndex++;
        }
        Map<Long, OrderRowResp> couponOrderMap = new HashMap<>();
        for (OrderRowResp orderRowResp : orderRowResps) {
            couponOrderMap.put(orderRowResp.getOrderId(),orderRowResp);
        }
        List<Long> orderIds = orderRowResps.stream().map(OrderRowResp::getOrderId).collect(Collectors.toList());
        QueryWrapper<CouponOrder> couponOrderQueryWrapper = new QueryWrapper<>();
        couponOrderQueryWrapper.eq("source", SourceEnum.JD.getCode());
        if (orderIds.size() != 0) {
            couponOrderQueryWrapper.lambda().and(
                    couponOrderLambdaQueryWrapper -> couponOrderLambdaQueryWrapper.in(CouponOrder::getOrderSn, orderIds)
            );
        }
        List<CouponOrder> couponOrders = couponOrderMapper.selectList(couponOrderQueryWrapper);
        for (CouponOrder couponOrder : couponOrders) {
            if (!couponOrder.getOrderStatus().equals(couponOrderMap.get(Long.valueOf(couponOrder.getOrderSn())).getValidCode().byteValue())) {
                couponOrder.setOrderStatus(couponOrderMap.get(Long.valueOf(couponOrder.getOrderSn())).getValidCode().byteValue());
                couponOrder.setSettlementTime(DateUtils.parseDate(couponOrderMap.get(Long.valueOf(couponOrder.getOrderSn())).getFinishTime()));
                byte couponOrderStatus;
                switch (couponOrderMap.get(Long.valueOf(couponOrder.getOrderSn())).getValidCode()) {
                    case 16:
                        couponOrderStatus = 1;
                        break;
                    case 17:
                        couponOrderStatus = 2;
                        break;
                    default:
                        couponOrderStatus = 3;
                }
                couponOrder.setCouponOrderStatus(couponOrderStatus);
                couponOrder.setOrderStatus(couponOrderMap.get(Long.valueOf(couponOrder.getOrderSn())).getValidCode().byteValue());
                couponOrderMapper.updateById(couponOrder);
            }
        }
    }

    /**
     * 拉取
     *
     * @throws Exception
     */
    public void orderTask() throws Exception {
        boolean data = true;
        int pageIndex = 1;
        LinkedList<OrderRowResp> linkedList = new LinkedList<>();
//        JdClient client = new DefaultJdClient("https://api.jd.com/routerjson", "", "c02c79ce1d4aee0500f6c4c7766700fc", "7d361f4207934d438fe775a854c30e3a");
        while (data) {
            UnionOpenOrderRowQueryRequest request = new UnionOpenOrderRowQueryRequest();
            OrderRowReq orderReq = new OrderRowReq();
            orderReq.setFields("goodsInfo");
            orderReq.setPageIndex(pageIndex);
            orderReq.setPageSize(500);
            orderReq.setType(1);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.MINUTE, -59);
            orderReq.setStartTime(DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss"));
            orderReq.setEndTime(DateUtil.getTime());
//            orderReq.setStartTime("2021-01-13 16:45:50");
//            orderReq.setEndTime("2021-01-13 16:45:50");
            request.setOrderReq(orderReq);
            UnionOpenOrderRowQueryResponse response = client.execute(request);
            logger.info("开始拉取订单时间[{}]", DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss"));
            logger.info("结束拉取订单时间[{}]", DateUtil.getTime());
            logger.info("拉取订单的信息为[{}]", JSON.toJSONString(response));
            if (!response.getQueryResult().getHasMore() || response.getQueryResult().getData().length == 0) {
                logger.info("拉取终止循环");
                data = false;
            }
            logger.info("拉取继续循环");
            List<OrderRowResp> orderRowRespList = Arrays.asList(response.getQueryResult().getData());
            linkedList.addAll(orderRowRespList);
            pageIndex++;
        }
        QueryWrapper<CouponOrder> couponOrderQueryWrapper = new QueryWrapper<>();
        couponOrderQueryWrapper.lambda().eq(CouponOrder::getSource, 2).orderByDesc(CouponOrder::getOrderTime).last("limit 1");
        CouponOrder couponOrders = couponOrderMapper.selectOne(couponOrderQueryWrapper);
        Date lastTime = null;
        if (couponOrders != null) {
            lastTime = couponOrders.getOrderTime();
        }
        for (OrderRowResp orderRowResp : linkedList) {
            if (lastTime != null && DateUtil.parse(orderRowResp.getOrderTime(), "yyyy-MM-dd HH:mm:ss").compareTo(lastTime) < 1) {
                linkedList.remove();
                //过滤待付款订单
            } else if (orderRowResp.getValidCode() != 15) {
                CouponOrder couponOrder = new CouponOrder();
                couponOrder.setUid(Integer.valueOf(orderRowResp.getSubUnionId()).longValue());
                couponOrder.setGoodsId(orderRowResp.getSkuId());
                couponOrder.setGoodsTitle(orderRowResp.getSkuName());
                couponOrder.setGoodsImage(orderRowResp.getGoodsInfo().getImageUrl());
                couponOrder.setOrderTime(DateUtil.parseTime(orderRowResp.getOrderTime()));
                couponOrder.setPayAmount(BigDecimal.valueOf(orderRowResp.getEstimateCosPrice()));
                couponOrder.setGoodsPrice(BigDecimal.valueOf(orderRowResp.getPrice()));
                couponOrder.setPayTime(DateUtil.parseTime(orderRowResp.getPayMonth()));
                couponOrder.setPromotionRate(BigDecimal.valueOf(orderRowResp.getFinalRate()));
                couponOrder.setPromotionAmount(BigDecimal.valueOf(orderRowResp.getActualCosPrice()));
                couponOrder.setPromotionId(orderRowResp.getPositionId().toString());
                byte couponOrderStatus;
                switch (orderRowResp.getValidCode()) {
                    case 16:
                        couponOrderStatus = 1;
                        break;
                    case 17:
                        couponOrderStatus = 2;
                        break;
                    default:
                        couponOrderStatus = 3;
                }
                couponOrder.setCouponOrderStatus(couponOrderStatus);
                couponOrder.setGoodsQuantity(orderRowResp.getSkuNum());
                couponOrder.setOrderSn(orderRowResp.getOrderId().toString());
                couponOrder.setOrderStatus(orderRowResp.getValidCode().byteValue());
                couponOrder.setSource((byte) 2);
                couponOrderMapper.insert(couponOrder);
            }
        }
    }
}
